#include "server.h"
#include "mysql.h"
#include "redis.h"
#include "util.h"
#include <iostream>
#include <unistd.h>
#include <cstring>
#include <thread>
#include <arpa/inet.h>
#include "json.hpp" // 包含 JSON 解析库头文件

using json = nlohmann::json;

// Server 构造函数：初始化服务器
Server::Server() {
    // 创建套接字
    server_fd_ = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd_ == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 配置服务器地址
    address_.sin_family = AF_INET; // 设置地址族为 IPv4
    // 将 IP 地址字符串转换为网络字节序并存储在 address_ 结构中
    if (inet_pton(AF_INET, "192.168.1.95", &address_.sin_addr) <= 0) {
        perror("inet_pton failed");
        exit(EXIT_FAILURE);
    }
    // 设置端口号为 8080，使用网络字节序
    address_.sin_port = htons(1234);

    // 绑定套接字到指定的地址和端口
    if (bind(server_fd_, (struct sockaddr *)&address_, sizeof(address_)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 使套接字进入监听状态，最大连接数为 3
    if (listen(server_fd_, 3) < 0) {
        perror("listen failed");
        exit(EXIT_FAILURE);
    }
}

// Server::start 函数：启动服务器，接受并处理客户端连接
void Server::start() {
    std::cout << "Server started..." << std::endl;

    while (true) {
        int client_socket;
        struct sockaddr_in client_address;
        socklen_t client_address_len = sizeof(client_address);

        // 接受客户端连接
        client_socket = accept(server_fd_, (struct sockaddr *)&client_address, &client_address_len);
        if (client_socket < 0) {
            perror("accept failed");
            continue;
        }

        // 创建一个新线程来处理客户端连接
        std::thread(&Server::handleClient, this, client_socket).detach();
    }
}

// Server::handleClient 函数：处理客户端连接
void Server::handleClient(int client_socket) {
    char buffer[1024] = {0}; // 缓冲区用于存储接收到的数据
    int bytes_read = read(client_socket, buffer, 1024); // 读取客户端发送的数据

    if (bytes_read > 0) {
        std::cout << "Received: " << buffer << std::endl;

        try {
            // 解析接收到的 JSON 数据
            json received_json = json::parse(buffer);
            std::string email = received_json.at("email").get<std::string>(); // 获取 email
            std::string name = received_json.at("name").get<std::string>(); // 获取 name
            std::string password = received_json.at("password").get<std::string>(); // 获取 password

            // 调用 insert_user 函数将用户信息插入数据库
            insert_test_user(email.c_str(), name.c_str(), password.c_str());
            std::string response = "User registered successfully"; // 返回成功注册的消息

            // 将响应发送给客户端
            send(client_socket, response.c_str(), response.length(), 0);
        } catch (json::parse_error &e) {
            // 处理 JSON 解析错误
            std::cerr << "JSON parse error: " << e.what() << std::endl;
            std::string response = "Invalid JSON";
            send(client_socket, response.c_str(), response.length(), 0);
        } catch (json::out_of_range &e) {
            // 处理 JSON 键错误
            std::cerr << "JSON key error: " << e.what() << std::endl;
            std::string response = "Missing key in JSON";
            send(client_socket, response.c_str(), response.length(), 0);
        }
    }

    close(client_socket); // 关闭客户端连接
}
